package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 服务器端
 */
public class Server {
    /**
     * Java.net.ServerSocket:
     * 运行在服务端，主要作用有两个
     * 1.向系统申请服务器端口，客户端通过该端口与服务器端建立连接
     * 2.监听服务器端口，一旦有客户连接了，就会立即建立一个Socket对象与客户端进行交互
     */
    private ServerSocket serverSocket;
    //private List<PrintWriter> allOut = new ArrayList<>();
    //key:客户端的昵称  value:该客户端的输出流
    private ExecutorService threadPool = Executors.newFixedThreadPool(50);
    private Map<String, PrintWriter> allOut = new HashMap<>();

    public Server() {
        try {
            System.out.println("服务器已启动");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务器启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端连接了");

                Runnable handler = new ClientHandler(socket);
                threadPool.execute(handler);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    /**
     * 该线程任务用于负责与指定客户端通信
     */
    private class ClientHandler implements Runnable {
        private Socket socket;
        private String host;//记录客户端ip地址
        private String nickname;

        public ClientHandler(Socket socket) {
            this.socket = socket;
            //通过socket获取该客户端的ip地址
            host = socket.getInetAddress().getHostAddress();
        }

        public void run() {
            PrintWriter pw = null;
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                //读取客户端发送过来的第一行字符串一定是客户端的昵称
                nickname = br.readLine();
                /*
                通过socket获取输出流，用于将消息发送给该客户端
                 */
                OutputStream out = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw, true);

                //将对应该客户端的输出流存入到共享集合allOut中
                synchronized (allOut) {
                    //allOut.add(pw);
                    allOut.put(nickname, pw);
                }
                //广播该客户端上线了
                broadcast(nickname + "[" + host + "]" + "上线了，当前在线人数" + allOut.size());

                String message;
                while ((message = br.readLine()) != null) {
                    if (message.startsWith("@")) {
                        //如果消息是以"@"开始则为私聊功能
                        sendMessageToSomeone(message);
                    } else {
                        broadcast(nickname + "[" + host + "]" + "说:" + message);
                        //接收方为null，用于表示没有特定接收方，用来表示群聊
                        saveMessage(nickname, null, message);
                    }
                    //将消息发送给该客户端
                    //pw.println("客户端说:"+message);
                    //遍历allOut集合将消息发送给所有客户端
//                    for (PrintWriter o : allOut) {
//                        o.println(host + "说:" + message);
//                    }
                }
            } catch (IOException e) {
            } finally {
                //处理该客户端断开连接后的操作
                //将该客户端的输出流从共享集合allOut中删除
                synchronized (allOut) {
                    //allOut.remove(pw);
                    allOut.remove(nickname);
                }
                //广播消息，告知所有客户端该客户端下线了
                broadcast(host + "下线了，当前在线人数" + allOut.size());
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        /**
         * 将消息发送给所有客户端
         *
         * @param message
         */
        private void broadcast(String message) {
            System.out.println(message);
            synchronized (allOut) {
//                for (PrintWriter o : allOut) {
//                    o.println(message);
//                }
                for (PrintWriter o : allOut.values()) {
                    o.println(message);
                }
            }
        }

        private void sendMessageToSomeone(String message) {
            /*
                过程：
                私聊消息的格式-->对方昵称:聊天消息
                1.截取出对方的昵称172.40.147.128
                substring()-->截“@”到“:”之间的内容
                2.从allOut中使用对方的昵称作为key提取到对应的输出流
                map.get(对方昵称)
                3.将聊天信息通过该输出流发送给对方
                聊天信息substring()->":"后面的内容
                然后通过输出流发送给对象
             */
            if (message.matches("@.+:.+")) {
                //1
                String toNickName = message.substring(1, message.indexOf(":"));
                //必要的验证，该用户是否存在
                if (allOut.containsKey(toNickName)) {
                    //2
                    PrintWriter pw = allOut.get(toNickName);
                    //3
                    String toMessage = message.substring(message.indexOf(":") + 1);
                    pw.println(nickname + "悄悄对你说:" + toMessage);
                    //4将私聊信息保存到数据库中
                    saveMessage(nickname, toNickName, toMessage);
                } else {
                    PrintWriter pw = allOut.get(toNickName);
                    pw.println("该用户不存在");
                }
            } else {
                //如果格式不正确，给当前用户提示私聊格式不正确
                PrintWriter pw = allOut.get(nickname);
                pw.println("私聊格式不正确，请重新输入,格式应当为@对方昵称:私聊消息");
            }
        }

        private void saveMessage(String fromUser, String toUser, String message) {
            /*
                将三个信息插入到chatinfo表
             */
            try (
                    Connection con = DBUtil.getConnection();
            ) {
                String sql = "INSERT INTO chatinfo(fromuser,touser,message) " +
                        "VALUES (?,?,?)";
                PreparedStatement ps = con.prepareStatement(sql);
                ps.setString(1, fromUser);
                ps.setString(2, toUser);
                ps.setString(3, message);
                ps.executeUpdate();
                int num= ps.executeUpdate();
                if (num>0){
                    System.out.println("保存成功");
                }else {
                    System.out.println("保存失败");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}